package com.company.transport;

import com.company.utils.CloseUtils;

import java.io.*;

public class FileReceiver implements Receiver {


    @Override
    public void receive(DataInputStream dataInputStream) throws IOException {
        while (dataInputStream.readInt() != -1) {
            String fileName = dataInputStream.readUTF();
            System.out.println("开始接收"+fileName);
            String filePath = dataInputStream.readUTF();//相对于父文件的文件路径
            long fileLength = dataInputStream.readLong();
            File dir = new File(filePath);
            if(!dir.exists()){
                dir.mkdirs();
            }
            File file = new File(filePath, fileName);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            byte[] cache = new byte[1024 * 5];
            long remain = fileLength;
            long currentLength = 0;
            long lastCurrentProgress = 0;
            while (remain > 0) {
                int cacheLength = cache.length<remain?cache.length: (int) remain;
                int len = dataInputStream.read(cache,0,cacheLength);
                fileOutputStream.write(cache,0,len);
                remain-=len;

                currentLength += len;
                float percent = currentLength * 1.0f / fileLength;
                int currentProgress = (int) (percent * 100);
                if (lastCurrentProgress + 5 < currentProgress || currentProgress == 100) {
                    System.out.println(fileName + currentProgress + "%");
                    lastCurrentProgress = currentProgress;
                }
            }
            fileOutputStream.flush();
            CloseUtils.closeIO(fileOutputStream);
        }


    }
}
